package conceptmaniax.hotelapp.activities;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.TimePicker;
import android.widget.TimePicker.OnTimeChangedListener;
import conceptmaniax.hotelapp.adapters.FeedbackListAdapter;
import conceptmaniax.hotelapp.adapters.ServiceListAdapter;
import conceptmaniax.hotelapp.config.Constants;
import conceptmaniax.hotelapp.enums.Language;
import conceptmaniax.hotelapp.managers.RequestManager;
import conceptmaniax.hotelapp.pojos.Service;
import conceptmaniax.hotelapp.util.GeneralUtils;
import conceptmaniax.hotelapp.util.database.DataHelper;

public class FormActivity extends Activity {
	private Language language;
	private String name;
	private String action;
	private String menu_id;
	private DataHelper dataHelper = new DataHelper(this, Constants.DATABASE_NAME);
	protected ImageView mainImage;
	private List<Service> serviceList = new ArrayList<Service>();
	private List<Service> serviceSelectionList = new ArrayList<Service>();
	private ServiceListAdapter serviceAdapter;
	private FeedbackListAdapter feedbackAdapter;
	protected Button showInfo;
	protected Button showServices;
	protected Button showGuide;
	protected Button showBooking;
	protected TableLayout callout;
	protected ListView callout_list;
	protected ScrollView homeScreen;
	protected Button requests;
	protected EditText txt_date;
	protected EditText txt_notes;
	protected TextView counter;
	protected Button submit;
	protected String[] temp;
	
	final SimpleDateFormat defaultDateFormat = new SimpleDateFormat("dd/M/yyyy, HH:mm",Locale.getDefault());
	final SimpleDateFormat cmsDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.getDefault());
    int hours;
    int minute;
	
	@Override
	protected void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.form);
		language = GeneralUtils.getLanguage(this);
		
		//Go back to HomePage Button
		final Button go_to_home = (Button) findViewById(R.id.homeButton);
			go_to_home.setOnClickListener(new View.OnClickListener() {
			public void onClick(final View view) {
		    	final Intent homePageIntent = new Intent(Constants.HOMEPAGE_ACTIVITY);
		    	startActivity(homePageIntent);
			}
		});

			// Parse String array from previous intent
			name = getIntent().getExtras().getString("name");
			action = getIntent().getExtras().getString("action");
			menu_id = getIntent().getExtras().getString("menu_id");
	     	mainImage = (ImageView)findViewById(R.id.form_main_image);
	     	
			final TextView serviceTitle = (TextView)findViewById(R.id.service_title);
	   		serviceTitle.setText(name);
	   		
	   		txt_date = (EditText) findViewById(R.id.date_textView);
	   		txt_notes = (EditText) findViewById(R.id.notes_textView);
	   		submit = (Button) findViewById(R.id.submit);
			showInfo = (Button) findViewById(R.id.hotel_button);
			showServices = (Button) findViewById(R.id.services_button);
			showGuide = (Button) findViewById(R.id.guide_button);
			showBooking = (Button) findViewById(R.id.booking_button);
			homeScreen = (ScrollView) findViewById(R.id.form_main_layout);
	 		requests = (Button) findViewById(R.id.requestsButton);
			callout = (TableLayout)findViewById(R.id.callout_table);
			callout_list = (ListView)findViewById(R.id.callout_listview);
			counter = (TextView) findViewById(R.id.counter);

		    int y =  this.getResources().getIdentifier(action,"drawable", this.getPackageName());
		    mainImage.setImageResource(y);
	}
			
	protected void initRegularForm() {
		
		txt_date.setOnFocusChangeListener(new View.OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
 				if (hasFocus) {
	 				disableSoftInputFromAppearing(txt_date);
	 				setdate(v);
 				}
			}
		});
			
			txt_notes.setOnEditorActionListener(new OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView v, int keyCode, KeyEvent event) {
				if ((event != null) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {               
	   		           InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
	   		           im.hideSoftInputFromWindow(homeScreen.getWindowToken(), 0);
	   		        }		
				return false;
			}
			});
		
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
	
		submit.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View r) {
					String currentDateandTime = defaultDateFormat.format(new Date());
					RequestManager.getInstance().storeRequests(txt_notes.getText().toString(), txt_date.getText().toString(), currentDateandTime, menu_id , serviceSelectionList);
				final Intent RequestIntent = new Intent(getBaseContext(),RequestListActivity.class);
				startActivity(RequestIntent);
				}
	 	});	
		
			fillFields(menu_id);
			this.serviceAdapter = new ServiceListAdapter(this, serviceList);
			final LinearLayout list = (LinearLayout) findViewById(R.id.form_listview);
			for(int i=0;i<serviceAdapter.getCount();i++) {
			    final View v = serviceAdapter.getView(i, null, null);
				final ImageView check = (ImageView) v.findViewById(R.id.form_check);
			    final int position = i;
			    v.setOnClickListener(new View.OnClickListener() {
			    	@Override
			    	public void onClick(View r) {
			            if (!v.isSelected()) {
				            v.setSelected(true);
				            check.setVisibility(View.VISIBLE);
			    			serviceSelectionList.add(new Service(serviceList.get(position).getId(),serviceList.get(position).getName()));
			            } else if (v.isSelected()) {
				            v.setSelected(false);
				            check.setVisibility(View.INVISIBLE);
			            	int pos = serviceAdapter.getItemViewType(position);
			    			serviceSelectionList.remove(pos);
			            }
			    	  }
			    	});	
			    list.addView(v,new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT));
			   }	
	}
	
	@SuppressLint("NewApi")
	public static void disableSoftInputFromAppearing(EditText editText) {
	    if (Build.VERSION.SDK_INT >= 11) {
	        editText.setRawInputType(InputType.TYPE_CLASS_TEXT);
	        editText.setTextIsSelectable(true);
	    } else {
	        editText.setRawInputType(InputType.TYPE_NULL);
	        editText.setFocusable(true);
	    }
	}
	
	protected void initFeedbackForm() {
		TableLayout notes = (TableLayout) findViewById(R.id.form_user_data);
		notes.setVisibility(View.GONE);
		fillFields(menu_id);
	    
		this.feedbackAdapter = new FeedbackListAdapter(this, serviceList);
	    temp = new String [feedbackAdapter.getCount()];
		final LinearLayout list = (LinearLayout) findViewById(R.id.form_listview);
		for(int i=0;i<feedbackAdapter.getCount();i++) {
		    final View v = feedbackAdapter.getView(i, null, null);
    		final int y = i;
		    RadioGroup rg = (RadioGroup) v.findViewById(R.id.radioGroup1);
		    rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {
		    	@Override	
		    	public void onCheckedChanged(RadioGroup group, int checkedId) {
				    String value = ((RadioButton) v.findViewById(checkedId )).getText().toString();   
				    temp[y] = value;
		    	}
		    });
		    list.addView(v,new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT));
		}

		submit.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View r) {
				    final AlertDialog.Builder builder = new AlertDialog.Builder(FormActivity.this);
					final AlertDialog dialog;
					String close = getBaseContext().getString(R.string.close_en);
					builder.setTitle("Thank you");
					builder.setMessage("Thank you for your feedback!");
					builder.setNegativeButton(close, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(final DialogInterface dialog, final int which) {
							dialog.cancel();
						}
					});
					dialog = builder.create();
					dialog.show();
					Log.i("Feedback:"," "+Arrays.toString(temp));
					final Intent HomepageIntent = new Intent(getBaseContext(),HomepageActivity.class);
					startActivity(HomepageIntent);
			}
		});	
	}
	
	private void fillFields (String type) {
		String serviceQuery = null;
		serviceQuery = "SELECT _id, "
					+ "name "
					+ "FROM service "
					+ "WHERE menu_id='" + menu_id + "'";		

		Cursor cursor =	dataHelper.getData(serviceQuery);
		while (cursor.moveToNext()) {
			serviceList.add(new Service(cursor.getInt(0), cursor.getString(1) ));
		}
		cursor.close();
		if ( this.dataHelper != null ) this.dataHelper.close();

	}
		
	public	 void setdate(View v) {

		final Dialog dialog = new Dialog(this);
	    dialog.setContentView(R.layout.date_picker);
	    dialog.setCancelable(true);
	    dialog.setTitle("");
	    dialog.show();
	    	    
	    TimePicker time_picker = (TimePicker) dialog.findViewById(R.id.timePicker1);
	    time_picker.setOnTimeChangedListener(new OnTimeChangedListener()
	    {
			@Override
	        public void onTimeChanged(TimePicker view, int hourOfDay, int minutes)
	        {
	            hours = hourOfDay;
	            minute = minutes;
	        }
	    });

	    final DatePicker date_picker = (DatePicker) dialog.findViewById(R.id.datePicker1);
	    Button btn = (Button) dialog.findViewById(R.id.buttondatetime);
	    btn.setOnClickListener(new OnClickListener()
	    {
	    	@Override
	        public void onClick(View arg0)
	        {
	    		EditText txt = (EditText) findViewById(R.id.date_textView);
	            String temp = "" + date_picker.getDayOfMonth() + "/" + (date_picker.getMonth() + 1) + "/"
	                    + date_picker.getYear()+", "+ hours + ":" +minute;
				try {
				    Date requestDate = defaultDateFormat.parse(temp);
				    String curStr = defaultDateFormat.format(requestDate);
		            txt.setText(curStr);
				} catch (ParseException e) {
					e.printStackTrace();
				}
	            dialog.cancel();
	        }
	     });
	}
		
	@Override
	protected void onResume() {
		super.onResume();
		SetButtonActivity.getInstance().setRecognition(false);
		SetButtonActivity.getInstance().setButtons(this, showInfo, showServices, showGuide, showBooking, callout, callout_list, homeScreen, requests);
		try {
			int counter = RequestManager.getInstance().getRequestCount();
			this.counter.setText(""+counter);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    // manage message counter
	    if (this.counter.getText().equals("0")) 
	        this.counter.setVisibility(View.INVISIBLE);
	     else
	        this.counter.setVisibility(View.VISIBLE);
		//action = getIntent().getExtras().getString("action");
	    if (action.equals("feedback")) 
	    	initFeedbackForm();
	     else
	    	initRegularForm();
	}
	
	@Override
	public boolean onCreateOptionsMenu(final Menu menu) {		
		return super.onCreateOptionsMenu(GeneralUtils.createOptionsMenu(this, menu));
	}
	
	@Override
	public boolean onOptionsItemSelected(final MenuItem item) {
		GeneralUtils.onOptionsItemSelected(this, item);
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	protected Dialog onCreateDialog(final int id) {
		return GeneralUtils.createAboutUsDialog(this);
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		unbindDrawables(findViewById(R.id.form_relative));
	    System.gc();  
	}
	
	private void unbindDrawables(View view) {
        if (view.getBackground() != null) {
        	view.getBackground().setCallback(null);
        }
        
        if (view instanceof ViewGroup && !(view instanceof AdapterView)) {
            for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
            	unbindDrawables(((ViewGroup) view).getChildAt(i));
            }
            ((ViewGroup) view).removeAllViews();
        }
    }
	
}